#!/bin/bash -ex
set -e -o pipefail

find_latest_gdb_version() {
    git ls-remote --tags git://sourceware.org/git/binutils-gdb.git \
        | grep -v users \
        | grep -v '{}' \
        | grep -oh 'gdb-[0-9]\{1,2\}\.[0-9]\{1,2\}\(\.[0-9]\{1,2\}\(\.[0-9]\{1,2\}\)\?\)\?-release' \
        | sort --version-sort -r \
        | sed 's/gdb-//g' \
        | sed 's/-release//g' \
        | head -n 1
}

VERSION=$(find_latest_gdb_version)
echo $VERSION > gdb_version

rm -rf "gdb" || true
curl "https://ftp.gnu.org/gnu/gdb/gdb-$VERSION.tar.gz" | tar xz
mv "gdb-$VERSION" "gdb"

set +x
# move to ctftools virtual env
source ctf-tools-venv-activate
set -x

PREFIX=$(pwd)

pushd ./gdb
./configure \
    --prefix=$PREFIX \
    --with-python=$(which python) \
    --enable-targets=all \
    --with-guile=guile-2.0
make -j $(nproc)
make install
# remove build artifacts
make clean
popd

# reduce binary size a little...
strip bin/gdb || true
strip bin/gdbserver || true
